package com.stox.services.data.downloader.model;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.stox.shared.core.model.Bar;
import com.stox.shared.core.model.Exchange;
import com.stox.shared.core.model.enumeration.BarSpan;
import com.stox.shared.core.model.intf.Callback;
import com.stox.shared.core.util.DateUtil;

public abstract class AbstractExchangeDataDownloader extends AbstractDataDownloader<Exchange> implements ExchangeDataDownloader {

	@Override
	public void download(Exchange exchange, BarSpan barSpan, Date start,
			Date end, Callback<List<Bar>, Void> callback) {
		if(!isCancelRequested() && !isRunning()){
			try{
				setRunning(true);
				
				final Calendar calendar = Calendar.getInstance();
				calendar.setTime(start);
				while (!calendar.getTime().after(end) && !isCancelRequested()) {
					calendar.add(barSpan.getUnit(), barSpan.getCount());
					if(DateUtil.isWeekend(calendar)){
						continue;
					}
					try{
						download(exchange, barSpan, calendar.getTime(), callback);
					}catch(Throwable t){
						t.printStackTrace();
					}
				}
				/**
				 * Execute callback with null argument to say that there is no more data to provide
				 */
				callback.execute(null);
			}catch (Throwable t) {
				t.printStackTrace();
			}finally{
				setRunning(false);
			}
		}
	}
	
	protected abstract void download(Exchange exchange, BarSpan barSpan, Date date, Callback<List<Bar>, Void> callback);
}
